package logic

import (
	"box-mart-api/moder"
	"context"
	"errors"

	"box-mart-api/boxrpc/boxrpc"
	"box-mart-api/boxrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *boxrpc.GoodsAddRequest) (*boxrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	var class moder.Class

	moder.DB.Debug().Where("name=?", in.ClassName).Find(&class)
	if class.ID == 0 {
		m := moder.Class{
			Name: in.ClassName,
		}
		moder.DB.Debug().Create(&m)
	}

	var goods moder.Goods
	moder.DB.Debug().Where("title=?", in.Title).Find(&goods)
	if goods.ID != 0 {
		return nil, errors.New("当前商品已存在，请更换")
	}
	goods = moder.Goods{
		Title:   in.Title,
		Price:   in.Price,
		ClassId: int64(class.ID),
	}
	err := goods.GoodsAdd(moder.DB)
	if err != nil {
		return nil, err
	}

	return &boxrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
